package com.dragon.manage.util;

import java.io.IOException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.dragon.manage.bean.AmusementInfo;
import com.dragon.manage.bean.AmusementType;
import com.dragon.manage.bean.ManageUser;
import com.dragon.manage.bean.MatchInfo;
import com.dragon.manage.bean.OddsInfoTmp;
import com.dragon.manage.bean.Recharge;
import com.dragon.manage.bean.TeamInfo;
import com.dragon.manage.bean.UserBet;
import com.dragon.manage.bean.UserInfo;
import com.dragon.manage.dao.IAmusementInfoDAO;
import com.dragon.manage.dao.IAmusementTypeDAO;
import com.dragon.manage.dao.IManageUserDAO;
import com.dragon.manage.dao.IMatchInfoDAO;
import com.dragon.manage.dao.ITeamInfoDAO;
import com.dragon.manage.service.IManageService;
import com.opensymphony.xwork2.ActionContext;

public class ManageUtil{
	/**
	 * 获取cookies中的用户id
	 * @param request
	 * @return
	 * @throws InvalidKeyException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 * @throws IOException
	 * @throws NoSuchPaddingException 
	 * @throws NoSuchAlgorithmException 
	 */
	  public static int getManageUserId(HttpServletRequest request) throws  Exception{
	    	Cookie[] cookies = request.getCookies();
	    	String pwdTmp = null;
	    	for(Cookie tmp:cookies){
	    		if(tmp.getName().equals(StaticData.SESSION_ID_KEY)){
	    			pwdTmp = tmp.getValue();
	    		}
	    	}
	    	
	    	String manageUserId = "";
	    	if(pwdTmp!=null&&!pwdTmp.isEmpty()){
	    		manageUserId = EncryUtil.decrypt(pwdTmp);
	    	}
	    	int mUid = StaticData.no_param;
	    	if(manageUserId!=null&&!manageUserId.isEmpty()){
	    		mUid = Integer.parseInt(manageUserId);
	    	}
	    	return mUid;
	    }
	/**
	 * 
	 * 根据session获取管理用户信息
	 * @param ct
	 * @param result
	 * @param session
	 * @param manageService
	 * @param rightId
	 * @return
	 * @throws Exception
	 */
	public static ManageUser getManageUserBySession(ActionContext ct,JSONObject result,
			HttpServletRequest request,IManageService manageService,int rightId) throws Exception{
		/*
		 * 在session中获取用户id
		 */
		int id =getManageUserId(request);
		if(id==StaticData.no_param){
			result.put(StaticData.reKey.code.getKey(), StaticData.codeType.user_not_login.getType());
			return null;
		}
		/*
		 * 再通过sessionid获取用户信息
		 */
		ManageUser manageUser = manageService.getManageUser(id);
		if(manageUser==null
				||manageUser.getUserStatus()==StaticData.userType.black.getType()
				||manageUser.getUserStatus()==StaticData.userType.delete.getType()){
			result.put(StaticData.reKey.code.getKey(), StaticData.codeType.not_is_user.getType());
			return null;
		}
		/*
		 * 验证权限
		 */
		if(!RightUtil.isHaveRight(manageUser, rightId)){
			result.put(StaticData.reKey.code.getKey(), StaticData.codeType.NO_RIGHT.getType());
			return null;
		}
		return manageUser;
	}
	
	/**
	 * 
	 * 获取比赛页面所需信息
	 * @param tmp
	 * @param teamInfoDAO
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getMatchPage(MatchInfo tmp,ITeamInfoDAO teamInfoDAO) throws Exception{
		TeamInfo teamTmp = null;
		JSONObject jsTmp = new JSONObject();
		jsTmp.put("id",tmp.getId());
		teamTmp = teamInfoDAO.getTeamInfoByID(tmp.getHostTeam());
		jsTmp.put("hostTeam", teamTmp.getTeamName());
		jsTmp.put("hostScore", tmp.getHostScore());
		teamTmp = teamInfoDAO.getTeamInfoByID(tmp.getGuestTeam());
		jsTmp.put("guestTeam", teamTmp.getTeamName());
		jsTmp.put("guestScore", tmp.getGuestScore());
		jsTmp.put("betTimes",tmp.getRelBetTimes());
		jsTmp.put("betMoney",tmp.getBetMoney());
		
		jsTmp.put("startTime",TimeUtil.getDateFormat(tmp.getStartDate()));
		jsTmp.put("endTime",TimeUtil.getDateFormat(tmp.getEndDate()));
		jsTmp.put("gameType",tmp.getGameType());
		jsTmp.put("matchStatus",tmp.getMatchStatus());
		jsTmp.put("matchTitle",tmp.getMatchTitle());
		jsTmp.put("matchImage",tmp.getMatchImage());
		return jsTmp;
	}
	
	/**
	 * 
	 * 获取奖金分配页面所需信息
	 * @param tmp
	 * @param teamInfoDAO
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getAwardDistributionPage(MatchInfo tmp,
			ITeamInfoDAO teamInfoDAO,IManageUserDAO manageUserDAO) throws Exception{
		TeamInfo teamTmp = null;
		ManageUser manageUser = null;
		JSONObject jsTmp = new JSONObject();
		jsTmp.put("id",tmp.getId());
		teamTmp = teamInfoDAO.getTeamInfoByID(tmp.getHostTeam());
		jsTmp.put("hostTeam", teamTmp.getTeamName());
		
		teamTmp = teamInfoDAO.getTeamInfoByID(tmp.getGuestTeam());
		jsTmp.put("guestTeam", teamTmp.getTeamName());
		manageUser = manageUserDAO.getManageUserByID(tmp.getFirstResult());
		jsTmp.put("firstResult",manageUser.getUserName());
		
		manageUser = manageUserDAO.getManageUserByID(tmp.getSecondResult());
		jsTmp.put("secondResult",manageUser.getUserName());
		jsTmp.put("profit",tmp.getProfit());
		jsTmp.put("matchStatus",tmp.getMatchStatus());
		return jsTmp;
	}
	
	/**
	 * 白名单用户列表
	 * @param tmp
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getWhiteUserPage(UserInfo tmp) throws Exception{
		JSONObject jsTmp = new JSONObject();
		jsTmp.put("id",tmp.getId());
		jsTmp.put("nickname",tmp.getNickname());
		jsTmp.put("userGold",tmp.getGold());
		jsTmp.put("type",tmp.getType());
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		jsTmp.put("createDate",format.format(tmp.getCreateDate()));
		return jsTmp;
	}
	
	/**
	 * 白名单用户列表
	 * @param tmp
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getUserBetListPage(UserBet tmp) throws Exception{
		JSONObject jsTmp = new JSONObject();
		jsTmp.put("id",tmp.getId());
//		AmusementInfo amusementInfo = amusementInfoDAO.getAmusementInfoByID(tmp.getAmusementId());
//		jsTmp.put("nickname",amusementInfo.get);
		jsTmp.put("betAmount",tmp.getBetAmount());
		jsTmp.put("profit",tmp.getProfit());
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		jsTmp.put("betDate",format.format(tmp.getCreateDate()));
		return jsTmp;
	}
	/**
	 * 充值前台列表
	 * @param tmp
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getUserRechargeListPage(Recharge tmp) throws Exception{
		JSONObject jsTmp = new JSONObject();
		jsTmp.put("id",tmp.getId());
		jsTmp.put("userId",tmp.getUserId());
//		jsTmp.put("userName",userInfo.getNickname());
		jsTmp.put("orderNo",tmp.getOrderNoLocal());
		jsTmp.put("money",tmp.getDiamond());
		if(tmp.getCompleteDate()!=null){
			jsTmp.put("completeDate",TimeUtil.getDateFormat(tmp.getCompleteDate()));
		}
		jsTmp.put("thirdPlatformId",tmp.getThirdPlatformId());
		return jsTmp;
	}
	/**
	 * 获取竞猜信息列表
	 * @param tmp
	 * @return
	 * @throws Exception 
	 */
	public static JSONObject getAmusementInfoPage(AmusementInfo tmp,IAmusementTypeDAO amusementTypeDAO,
			IMatchInfoDAO matchInfoDAO, ITeamInfoDAO teamInfoDAO) throws Exception{
		MatchInfo matchInfo = matchInfoDAO.getMatchInfoByID(tmp.getMatchId());
		TeamInfo hostTeam = teamInfoDAO.getTeamInfoByID(matchInfo.getHostTeam());
		TeamInfo guestTeam = teamInfoDAO.getTeamInfoByID(matchInfo.getGuestTeam());
		AmusementType amusementTypeTmp = amusementTypeDAO.getAmusementTypeByID(tmp.getAmusementType());
		StringUtil.replaceSign(amusementTypeTmp, hostTeam, guestTeam);
		JSONObject jsTmp = new JSONObject();
		jsTmp.put("id", tmp.getId());
		jsTmp.put("amusementType", tmp.getAmusementType());
		jsTmp.put("amusementTypeName", amusementTypeTmp.getName());
		jsTmp.put("amusementResult", tmp.getAmusementResult());
		jsTmp.put("oddsInfo", tmp.getOddsInfo());
		jsTmp.put("matchStatus", tmp.getMatchStatus());
		jsTmp.put("startTime",TimeUtil.getDateFormat(tmp.getCreateDate()));
		jsTmp.put("endTime",TimeUtil.getDateFormat(tmp.getEndDate()));
		jsTmp.put("oddsType", tmp.getOddsType());
		return jsTmp;
	}
	
	/**
	 * 转换后台管理员用户列表需要的字段
	 * @param manageUser
	 * @return
	 */
	public static JSONObject getManageUserPage(ManageUser manageUser){
		JSONObject reJs = new JSONObject();
		reJs.put("id", manageUser.getId());
		reJs.put("rightId", manageUser.getUserRight());
		reJs.put("userName", manageUser.getUserName());
		reJs.put("lastLoginIp", manageUser.getLoginIp());
		if(manageUser.getLoginDate()!=null){
			reJs.put("lastLoginDate", TimeUtil.getDateFormat(manageUser.getLoginDate()));
		}
		
		reJs.put("userStatus", manageUser.getUserStatus());
		return reJs;
	}
	
	/**
	 * 组装前端需要的比赛信息
	 * @param tmp
	 * @param amusementInfoDAO
	 * @param matchInfoDAO
	 * @param teamInfoDAO
	 * @param amusementTypeDAO
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getMatchInfoPage(UserBet tmp,IAmusementInfoDAO amusementInfoDAO,
			IMatchInfoDAO matchInfoDAO, ITeamInfoDAO teamInfoDAO,IAmusementTypeDAO amusementTypeDAO) throws Exception{
		/*
		 * 主客队
		 * 开盘的类型
		 * 当前状态
		 * 竞猜选项
		 * 投注金额
		 * 赔率
		 * 胜负
		 */
		JSONObject jsTmp= new JSONObject();
		AmusementInfo amusementInfo = amusementInfoDAO.getAmusementInfoByID(tmp.getAmusementId());
		MatchInfo matchInfo = matchInfoDAO.getMatchInfoByID(amusementInfo.getMatchId());
		TeamInfo hostTeam = teamInfoDAO.getTeamInfoByID(matchInfo.getHostTeam());
		TeamInfo guestTeam = teamInfoDAO.getTeamInfoByID(matchInfo.getGuestTeam());
		jsTmp.put("matchTitle", matchInfo.getMatchTitle());
		/*
		 * 我下注的选项
		 */
		Map<Integer, OddsInfoTmp> oddInfoMap =amusementInfo.getOddsInfoMap();
		if(oddInfoMap==null){
			LogUtil.error(tmp.getUserId()+"玩家下注数据异常，下注项目："+tmp.getAmusementId());
			return null;
		}
		OddsInfoTmp oddsInfoTmp = oddInfoMap.get(tmp.getBetType());
		if(oddsInfoTmp==null){
			LogUtil.error(tmp.getUserId()+"玩家下注数据异常，下注项目："+tmp.getAmusementId());
			return null;
		}
		
		jsTmp.put(StaticData.reKey.myBetName.getKey(), oddsInfoTmp.getOddsName());
		/*
		 * 主客队
		 */
		jsTmp.put(StaticData.reKey.HostTeam.getKey(), hostTeam.getTeamName());
		
		jsTmp.put(StaticData.reKey.GuestTeam.getKey(), guestTeam.getTeamName());
		
		/*
		 * 竞猜选项
		 */
		AmusementType type = amusementTypeDAO.getAmusementTypeByID(amusementInfo.getAmusementType());
		
		StringUtil.replaceSign(type, hostTeam, guestTeam);
		
		jsTmp.put(StaticData.reKey.amusementInfoType.getKey(), type.getName());
		
		jsTmp.put(StaticData.reKey.startDate.getKey(), TimeUtil.getDateFormat(tmp.getCreateDate()));
		/*
		 * 开盘状态
		 */
		int status = amusementInfo.getMatchStatus();
		if(status==StaticData.AmusementStatus.putaway.getType()&&TimeUtil.isTimeOut(amusementInfo.getEndDate())){
			status = StaticData.AmusementStatus.feng_pan.getType();
		}
		jsTmp.put(StaticData.reKey.amusementInfoStatus.getKey(), status);
		/*
		 * 投注金额
		 */
		jsTmp.put(StaticData.reKey.betCount.getKey(), tmp.getBetAmount());
		/*
		 * 赔率
		 */
		jsTmp.put(StaticData.reKey.odds.getKey(),decimals2(tmp.getOdds()));
		/*
		 * 胜负
		 */
		if(tmp.getBetStatus()==StaticData.userBetSettleType.win.getType()
				||tmp.getBetStatus()==StaticData.userBetSettleType.cancel.getType()){
			jsTmp.put(StaticData.reKey.profit.getKey(), tmp.getProfit()+tmp.getBetAmount());
		}else{
			jsTmp.put(StaticData.reKey.profit.getKey(), tmp.getProfit());
		}
		return jsTmp;
	}
	
	/**
	 * 保留两位小数
	 * @param f
	 * @return
	 */
	public static double decimals2(double f){
		BigDecimal   b   =   new   BigDecimal(f);  
		double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue(); 
		return f1;
	}
}
